package gw.com.android.model;

import android.text.TextUtils;

import com.gwtsz.android.rxbus.RxBus;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import gw.com.android.app.AppContances;
import gw.com.android.app.GTConfig;
import gw.com.android.terminal.AppTerminal;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.DoubleConverter;
import www.com.library.util.JsonUtil;
import www.com.library.util.StringUtils;

/**
 * Created by reeta.zou on 2016/7/6.
 * 界面数据管理类
 */
public class DataManager {

    private static final String TAG = "DataManager";
    private static DataManager instance = null;

    public synchronized static DataManager instance() {
        if (instance == null) {
            instance = new DataManager();
            instance.init();
        }
        return instance;
    }

    /**
     * 各界面数据是否加载完成标识统一处理
     */
    private ConcurrentHashMap<String, Boolean> mLoadDataStateMap;
    public DataItemDetail mAccount;
    /**
     * 行情产品报价数据
     */
    public ConcurrentHashMap<String, DataItemDetail> mTickMap;
    /**
     * 持仓信息列表
     */
    public DataItemResult mPositionInfoList;
    /**
     * 挂单列表
     */
    public DataItemResult mOrderInfoList;
    /**
     * 当日成交列表
     */
    public DataItemResult mDealInfoList;
    /**
     * 当日盈亏列表数据
     */
    public DataItemResult mCloseList;
    /**
     * 发送订阅的自选产品code
     */
    private ArrayList<Integer> mCodes;
    /**
     * 自选产品code
     */
    public ArrayList<Integer> mSelfCode;

    /**
     * 持仓条数
     */
    private ConcurrentHashMap<String, Integer> mPositionNumMap;

    private void init() {
        mLoadDataStateMap = new ConcurrentHashMap<>();
        mAccount = new DataItemDetail();
        mTickMap = new ConcurrentHashMap<>();
        mPositionInfoList = new DataItemResult();
        mOrderInfoList = new DataItemResult();
        mDealInfoList = new DataItemResult();
        mCloseList = new DataItemResult();
        mCodes = new ArrayList<>();
        mSelfCode = new ArrayList<>();
        mPositionNumMap = new ConcurrentHashMap<>();
    }

    /**
     * 清空相关数据
     */
    public void reset() {
        if (null != instance) {
            instance = null;
        }
        if (null != mLoadDataStateMap) {
            mLoadDataStateMap.clear();
            mLoadDataStateMap = null;
        }
        if (null != mAccount) {
            mAccount.clear();
            mAccount = null;
        }
        if (null != mTickMap) {
            mTickMap.clear();
            mTickMap = null;
        }
        if (null != mOrderInfoList) {
            mOrderInfoList.clear();
            mOrderInfoList = null;
        }
        if (null != mPositionInfoList) {
            mPositionInfoList.clear();
            mPositionInfoList = null;
        }
        if (null != mDealInfoList) {
            mDealInfoList.clear();
            mDealInfoList = null;
        }
        if (null != mCloseList) {
            mCloseList.clear();
            mCloseList = null;
        }
        if (null != mCodes) {
            mCodes.clear();
            mCloseList = null;
        }
        if (null != mSelfCode) {
            mSelfCode.clear();
            mSelfCode = null;
        }
        if (null != mPositionNumMap) {
            mPositionNumMap.clear();
            mPositionNumMap = null;
        }
    }

    /**
     * 清空订阅集合
     */
    public void clearCodes() {
        Logger.e(TAG, "订阅产品: 清理code避免下次发送相同的产品");
        if (null != mCodes) {
            mCodes.clear();
        }
    }

    /**
     * 设置资金信息
     */
    public void setAccount(String jsonStr) {
        try {
            JSONObject mArray = new JSONObject(jsonStr);
            mAccount.clear();
            JsonUtil.toDataItemDetail(mAccount, mArray);
            if ("".equals(GTConfig.instance().mCurName)) {
                GTConfig.instance().mCurName = mAccount.getString(GTSConst.JSON_KEY_NAME);
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 及时更新层级保证金的开关
     */
    public void updateMarginOff(int off) {
        mAccount.setBooleanValue(GTSConst.JSON_KEY_MARGINONOFF, (off == 1));
    }

    /**
     * 是否开启层级保证金
     */
    public boolean hasMargin() {
        return mAccount.getBoolean(GTSConst.JSON_KEY_MARGINONOFF);
    }

    /**
     * 判断用户信息是否存在
     */
    public boolean hasAccount() {
        if (mAccount.getCount() > 1) {
            return true;
        }
        return false;
    }

    /**
     * 返回是否人民币账号，true人民币，false美元
     */
    public boolean isCNY() {
        if (mAccount.getString(GTSConst.JSON_KEY_TYPE).equals("CNY")) {
            return true;
        }
        return false;
    }

    /**
     * 返回有产品的板块列表
     */
    public DataItemResult getFilterQuoteType(DataItemResult tmp) {
        DataItemResult result = new DataItemResult();
        for (int i = 0; i < tmp.getDataCount(); i++) {
            String type = tmp.getItem(i).getString(ConfigType.CONFIG_TYPE_TYPE_TAG);
            if (mLoadDataStateMap.containsKey(type + "") || type.equals(GTSConst.ZONE_TYPE_SELF + "")) {
                result.addItem(tmp.getItem(i));
            }
        }
        return result;
    }

    /**
     * 保存所有产品数据
     */
    public void addAllTickList(String jsonStr) {
        Logger.i(TAG, "addAllTickList receiver tick list ...");
        try {
            DataItemDetail item;
            JSONArray mArray = new JSONArray(jsonStr);
            mTickMap.clear();
            List<String> filterList = getFilterList();
            for (int i = 0; i < mArray.length(); i++) {
                JSONObject object = mArray.getJSONObject(i);
                item = new DataItemDetail();
                JsonUtil.toDataItemDetail(item, object);
                String name = item.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB);
                Logger.e(TAG, "QCMD_RES_PERTICK第一口行情报价name3 = " + name + ", sell = " + item.getString(GTSConst.JSON_KEY_SELLPRICE)
                        + ", " + item.getString(GTSConst.JSON_KEY_SELLPRICESTATE) + ", buy = " + item.getString(GTSConst.JSON_KEY_BUYPRICE)
                        + ", " + item.getString(GTSConst.JSON_KEY_BUYPRICESTATE) + ", " + item.getString(GTSConst.JSON_KEY_ZOOMRULE));
                if (filterList.contains(name)) {
                    Logger.e(TAG, "intercept this tick....name = " + name);
                    continue;
                }
                mTickMap.put(item.getInt(GTSConst.JSON_KEY_CODEID) + "", item);
            }
            Logger.e(TAG, "addAllTickList = " + mTickMap.size());
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    private List<String> getFilterList() {
        ArrayList<String> list = new ArrayList<>();
        list.add("伦敦金");
        list.add("伦敦银");
        list.add("离岸人民币黄金");
        list.add("离岸人民币白银");
        return list;
    }

    /**
     * 添加自选列表集合数据
     */
    public void addSelfTickList(String jsonStr) {
        Logger.i(TAG, "addSelfTickList receiver self tick list ...");
        List<String> filterList = getFilterList();
        try {
            JSONArray mArray = new JSONArray(jsonStr);
            mSelfCode.clear();
            for (int i = 0; i < mArray.length(); i++) {
                JSONObject object = mArray.getJSONObject(i);
                int codeID = object.getInt(GTSConst.JSON_KEY_CODEID);
                DataItemDetail item = mTickMap.get(String.valueOf(codeID));
                if (item != null) {
                    String name = item.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB);
                    if (filterList.contains(name)) {
                        Logger.i(TAG, "addSelfTickList . drop this self code. name = " + name);
                        continue;
                    }
                }
                mSelfCode.add(codeID);
                Logger.d(TAG, "" + object.getString("SymbolNameGB"));
            }
            setSelfSelect();
            Logger.i(TAG, "addSelfTickList receiver self tick list receiver size = " + mArray.length() + "  valide self code = " + mSelfCode.toString());
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 检查自选的产品
     * <p>
     * 当前自选产品为空时，默认会添加一些自选
     */
    public void validateSelfTick() {
        Logger.i(TAG, "validateSelfTick self tick check start!");
        if (!mSelfCode.isEmpty()) {//已选中的产品不为空，那么就不必强制添加
            Logger.i(TAG, "validateSelfTick self tick check start! not empty!");
            return;
        }

        Logger.i(TAG, "validateSelfTick self tick is empty,add default self tick");
        boolean added = GTConfig.instance().getBooleanValue(GTConfig.instance().mCurName + "_add_self_tick", false);
        if (added) {
            Logger.i(TAG, "validateSelfTick self tick only add once,it is already added. username = " + GTConfig.instance().mCurName);
            return;
        }
        List defaultList = getDefaultSelfList();
        DataItemResult mTmpList = getTickList(String.valueOf(GTSConst.ZONE_TYPE_ALL));
        // 判定当前列表的数目
        int count = 0;
        for (int i = 0; i < mTmpList.getDataCount(); i++) {
            DataItemDetail mTickModel = mTmpList.getItem(i);//
            //执行添加产品的过程
            String tempName = mTickModel.getString("SymbolNameGB");
            if (defaultList.contains(tempName)) {
                addSelfTick(mTickModel);
                count++;
            }
        }
        Logger.i(TAG, "validateSelfTick self tick ; I have added " + count + " ticks!");
        //RxBus.getInstance().post(GTSConst.REPLY_QUOTE_SELF, mTickModel);
        AppTerminal.instance().saveCustomer(getSelfCodes());
        GTConfig.instance().setBooleanValue(GTConfig.instance().mCurName + "_add_self_tick", true);
        //自动添加完成之后，发个通知，让界面列表更新数据
        RxBus.getInstance().post(GTSConst.REPLY_POP_REFRESH_ON_FIRST_INSTALL, false);
    }

    private List<String> getDefaultSelfList() {
        List<String> list = new ArrayList<>();
        list.add("欧元美元");//1
        list.add("澳元美元");//2
        list.add("英镑美元");//3
        list.add("美元日元");//4
        list.add("现货黄金");//5
        list.add("美国原油");//6
        list.add("香港50");//7
        list.add("美元加元");//8
        list.add("纽元美元");//9
        list.add("澳元纽元");//10
        list.add("欧元澳元");//11
        list.add("欧元日元");//12
        list.add("现货白银");//13
        list.add("天然气");//14
        list.add("美国TECH100");//15
        list.add("中华300");//16
        list.add("美元离岸人民币");//17
        list.add("澳元日元");//18
        list.add("英镑日元");//19
        list.add("纽元日元");//20
        return list;
    }


    private static List<String> recommendList;//推荐的产品
    private static List<String> guestList;//游客默认看到的产品
    private static List<String> filterList;//过滤列表

    static {
        recommendList = new ArrayList<>();
        recommendList.add("现货黄金");
        recommendList.add("欧元美元");
        recommendList.add("美元日元");
        recommendList.add("美国原油");
        recommendList.add("香港50");

        guestList = new ArrayList<>();
        guestList.add("伦敦金");
        guestList.add("伦敦银");
        guestList.add("离岸人民币黄金");
        guestList.add("离岸人民币白银");
        guestList.add("纽约期油");
        guestList.add("美元指数");

        filterList = new ArrayList<>();
        filterList.add("伦敦金");
        filterList.add("伦敦银");
        filterList.add("离岸人民币黄金");
        filterList.add("离岸人民币白银");
    }

    private List<String> getGuestList() {
        return guestList;
    }

    private List<String> getFilter() {
        return filterList;
    }

    private List<String> getRecommendList() {
        return recommendList;
    }

    /**
     * 判断一个产品，是不是推荐
     */
    public boolean ifRecommend(DataItemDetail item) {
        List<String> filterList = getRecommendList();
        String name = item.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB);
        if (filterList.contains(name.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存自选的最新排序位置
     */
    public void addSelfTickList(DataItemResult result) {
        Logger.i(TAG, "addSelfTickList edit self..");
        mSelfCode.clear();
        for (int i = 0; i < result.getDataCount(); i++) {
            mSelfCode.add(result.getItem(i).getInt(GTSConst.JSON_KEY_CODEID));
        }
        setSelfSelect();
        Logger.i(TAG, "addSelfTickList " + mSelfCode.size() + ", " + mSelfCode.toString());
    }

    /**
     * 设置自选标识
     */
    private void setSelfSelect() {
        Iterator<String> keys = mTickMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            DataItemDetail item = mTickMap.get(key);
            if (null == item) {
                continue;
            }
            boolean isFind = false;
            for (int i = 0; i < mSelfCode.size(); i++) {
                if (item.getInt(GTSConst.JSON_KEY_CODEID) == mSelfCode.get(i)) {
                    isFind = true;
                    break;
                }
            }
            if (isFind) {
                item.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 1);
            } else {
                item.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 0);
            }
        }
    }

    /**
     * 标识是否是自选产品
     */
    public boolean isSelfPro(int codeId) {
        boolean isFind = false;
        for (int i = 0; i < mSelfCode.size(); i++) {
            if (codeId == mSelfCode.get(i)) {
                isFind = true;
                break;
            }
        }
        return isFind;
    }

    /**
     * 获取可用，非参考产品
     * 热门界面需要用到
     */
    public DataItemResult getAllTickList() {
        Logger.i(TAG, "getAllTickList");
        DataItemResult mList = new DataItemResult();
        Iterator<String> keys = mTickMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            DataItemDetail item = mTickMap.get(key);
            if (null != item && item.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE
                    && item.getInt(GTSConst.JSON_KEY_ZONE) != GTSConst.ZONE_TYPE_REF) {
                mList.addItem(item);
            }
        }
        return mList;
    }

    /**
     * 根据类型返回行情集合对象
     */
    public DataItemResult getTickList(String type) {
        DataItemResult mList = new DataItemResult();
        Iterator<String> keys = mTickMap.keySet().iterator();
        Logger.i(TAG, "getTickList type = " + type + "  and size = " + mTickMap.size());
        while (keys.hasNext()) {
            String key = keys.next();
            DataItemDetail item = mTickMap.get(key);
            if (null != item && item.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE) {
                if (type.equals(item.getInt(GTSConst.JSON_KEY_ZONE) + "") || type.equals(GTSConst.ZONE_TYPE_ALL + "")) {
                    mList.addItem(item);
                }
            }
        }
        Collections.sort(mList.getDataList(), new Comparator<DataItemDetail>() {
            @Override
            public int compare(DataItemDetail o1, DataItemDetail o2) {
                if (null != o1 && null != o2) {
                    if (o1.getInt(GTSConst.JSON_KEY_ZONE) == o2.getInt(GTSConst.JSON_KEY_ZONE)) {
                        return StringUtils.sortPro(o2.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME), o1.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
                    } else if (o1.getInt(GTSConst.JSON_KEY_ZONE) > o2.getInt(GTSConst.JSON_KEY_ZONE)) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
                return 0;
            }
        });
        return mList;
    }

    /**
     * 根据类型返回行情集合对象
     */
    public DataItemResult getAllTradeTickList() {
        Logger.i(TAG, "getAllTradeTickList type ");
        DataItemResult mList = new DataItemResult();
        Iterator<String> keys = mTickMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            DataItemDetail item = mTickMap.get(key);
            if (null != item && item.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_ABLE) {
                mList.addItem(item);
            }
        }
        Collections.sort(mList.getDataList(), new Comparator<DataItemDetail>() {
            @Override
            public int compare(DataItemDetail o1, DataItemDetail o2) {
                if (null != o1 && null != o2) {
                    if (o1.getInt(GTSConst.JSON_KEY_ZONE) == o2.getInt(GTSConst.JSON_KEY_ZONE)) {
                        return StringUtils.sortPro(o2.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME), o1.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
                    } else if (o1.getInt(GTSConst.JSON_KEY_ZONE) > o2.getInt(GTSConst.JSON_KEY_ZONE)) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
                return 0;
            }
        });
        return mList;
    }

    /**
     * 根据类型返回根据涨跌排序的行情集合对象
     */
    public DataItemResult getSortTickList(DataItemResult tmp, final int type) {
        final int sortType = type;
        if (null != tmp && tmp.getDataCount() > 0) {
            if (sortType == AppContances.SORT_NORMAL_TYPE) {
                return tmp;
            }

            Collections.sort(tmp.getDataList(), new Comparator<DataItemDetail>() {
                @Override
                public int compare(DataItemDetail o1, DataItemDetail o2) {
                    if (null != o1 && null != o2) {

                        if (sortType == AppContances.SORT_SPEED_TYPE) {
                            if (Math.abs(DoubleConverter.toFloatData(o1.getString(GTSConst.JSON_KEY_PERCENT)))
                                    > Math.abs(DoubleConverter.toFloatData(o2.getString(GTSConst.JSON_KEY_PERCENT)))) {
                                return -1;
                            } else if (Math.abs(DoubleConverter.toFloatData(o1.getString(GTSConst.JSON_KEY_PERCENT)))
                                    == Math.abs(DoubleConverter.toFloatData(o2.getString(GTSConst.JSON_KEY_PERCENT)))) {
                                return 0;
                            } else {
                                return 1;
                            }
                        } else {
                            if (DoubleConverter.toFloatData(o1.getString(GTSConst.JSON_KEY_PERCENT))
                                    > DoubleConverter.toFloatData(o2.getString(GTSConst.JSON_KEY_PERCENT))) {
                                if (sortType == AppContances.SORT_UP_TYPE) {
                                    return 1;
                                } else if (sortType == AppContances.SORT_DOWN_TYPE) {
                                    return -1;
                                } else {
                                    return 0;
                                }
                            } else if (DoubleConverter.toFloatData(o1.getString(GTSConst.JSON_KEY_PERCENT))
                                    == DoubleConverter.toFloatData(o2.getString(GTSConst.JSON_KEY_PERCENT))) {
                                return 0;
                            } else {
                                if (sortType == AppContances.SORT_UP_TYPE) {
                                    return -1;
                                } else if (sortType == AppContances.SORT_DOWN_TYPE) {
                                    return 1;
                                } else {
                                    return 0;
                                }
                            }
                        }
                    } else {
                        return 0;
                    }
                }
            });
        }
        return tmp;
    }


    /**
     * 自选产品列表返回
     */
    public DataItemResult getSelfTickList() {
        DataItemResult mList = new DataItemResult();
        int num = mSelfCode.size();
        /*自选产品code*/
        ArrayList<Integer> mCode = new ArrayList<>();
        String code;
        for (int i = 0; i < num; i++) {
            code = mSelfCode.get(i).toString();
            DataItemDetail item = mTickMap.get(code);
            if (null != item && item.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE) {
                mList.addItem(item);
            } else {
                mCode.add(i);
            }
        }
        if (mCode.size() > 0) {
            for (int i = 0; i < mCode.size(); i++) {
                int position = mCode.get(i);
                if (position >= 0 && position < mSelfCode.size()) {
                    int uiCode = mSelfCode.get(position);
                    AppTerminal.instance().delSelectStock(uiCode);
                    mSelfCode.remove(position);
                }
            }
        }
        return mList;
    }

    /**
     * 更新其中一条item数据，找不到则不更新
     */
    public DataItemDetail updateTickList(int codeID, JSONObject model) {
        if (null == model) {
            return null;
        }
        //Logger.i(TAG, "updateTickList codeID = " + codeID);
        if (mTickMap.containsKey(codeID + "")) {
            DataItemDetail itemDetail = mTickMap.get(codeID + "");
            updateTickItem(itemDetail, model);
            return itemDetail;
        }
        return null;
    }

    /**
     * 更新其中一条产品更新数据，没有则添加
     */
    public DataItemDetail updateSymbolList(int codeID, JSONObject model) {
        if (null == model) {
            return null;
        }
        if (mTickMap.containsKey(codeID + "")) {
            DataItemDetail itemDetail = mTickMap.get(codeID + "");
            updateTickItem(itemDetail, model);
            return itemDetail;
        } else {
            DataItemDetail item = new DataItemDetail();
            JsonUtil.toDataItemDetail(item, model);
            mTickMap.put(codeID + "", item);
            return item;
        }
    }

    /**
     * 报价对象更新
     */
    private void updateTickItem(DataItemDetail oldItem, JSONObject newItem) {
        //报价更新
        if (newItem.optInt(GTSConst.JSON_KEY_CURPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_CURPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_CURPRICESTATE));
            oldItem.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, 0);
        } else {
            oldItem.setIntValue(GTSConst.JSON_KEY_CURPRICEARRAW, 1);
        }
        oldItem.setIntValue(GTSConst.JSON_KEY_CURPRICEBGSTATE, newItem.optInt(GTSConst.JSON_KEY_CURPRICESTATE));
        if (newItem.optInt(GTSConst.JSON_KEY_OPENPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_OPENPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_OPENPRICESTATE));
        }
        if (newItem.optInt(GTSConst.JSON_KEY_CLOSESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_CLOSESTATE, newItem.optInt(GTSConst.JSON_KEY_CLOSESTATE));
        }
        if (newItem.optInt(GTSConst.JSON_KEY_HIGHPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_HIGHPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_HIGHPRICESTATE));
        }
        if (newItem.optInt(GTSConst.JSON_KEY_LOWPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_LOWPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_LOWPRICESTATE));
        }
        if (newItem.optInt(GTSConst.JSON_KEY_BUYPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_BUYPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_BUYPRICESTATE));
            oldItem.setIntValue(GTSConst.JSON_KEY_BUYPRICEARRAW, 0);
        } else {
            oldItem.setIntValue(GTSConst.JSON_KEY_BUYPRICEARRAW, 1);
        }
        if (newItem.optInt(GTSConst.JSON_KEY_SELLPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_SELLPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_SELLPRICESTATE));
            oldItem.setIntValue(GTSConst.JSON_KEY_SELLPRICEARRAW, 0);
        } else {
            oldItem.setIntValue(GTSConst.JSON_KEY_SELLPRICEARRAW, 1);
        }

        oldItem.setStringValue(GTSConst.JSON_KEY_CURPRICE, newItem.optString(GTSConst.JSON_KEY_CURPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_OPENPRICE, newItem.optString(GTSConst.JSON_KEY_OPENPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_CLOSEPRICE, newItem.optString(GTSConst.JSON_KEY_CLOSEPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_HIGHPRICE, newItem.optString(GTSConst.JSON_KEY_HIGHPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_LOWPRICE, newItem.optString(GTSConst.JSON_KEY_LOWPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_BUYPRICE, newItem.optString(GTSConst.JSON_KEY_BUYPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_SELLPRICE, newItem.optString(GTSConst.JSON_KEY_SELLPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_ZOOMRULE, newItem.optString(GTSConst.JSON_KEY_ZOOMRULE));
        oldItem.setStringValue(GTSConst.JSON_KEY_DIFF, newItem.optString(GTSConst.JSON_KEY_DIFF));
        oldItem.setStringValue(GTSConst.JSON_KEY_RISE, newItem.optString(GTSConst.JSON_KEY_RISE));
        oldItem.setStringValue(GTSConst.JSON_KEY_PERCENT, newItem.optString(GTSConst.JSON_KEY_PERCENT));
        oldItem.setStringValue(GTSConst.JSON_KEY_CURPRICEMAP, newItem.optString(GTSConst.JSON_KEY_CURPRICEMAP));

        oldItem.setIntValue(GTSConst.JSON_KEY_TIME, newItem.optInt(GTSConst.JSON_KEY_TIME));
        oldItem.setIntValue(GTSConst.JSON_KEY_ASPOSITION, newItem.optInt(GTSConst.JSON_KEY_ASPOSITION));
//        oldItem.setIntValue(GTSConst.JSON_KEY_ISSELECTED, newItem.optInt(GTSConst.JSON_KEY_ISSELECTED));
        //产品更新
        oldItem.setIntValue(GTSConst.JSON_KEY_STARTTIME, newItem.optInt(GTSConst.JSON_KEY_STARTTIME));
        oldItem.setIntValue(GTSConst.JSON_KEY_DIGITS, newItem.optInt(GTSConst.JSON_KEY_DIGITS));
        oldItem.setIntValue(GTSConst.JSON_KEY_TRADESTATE, newItem.optInt(GTSConst.JSON_KEY_TRADESTATE));
        //产品不可用时，将自选标识设置成false
        if (newItem.optInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_ENABLE) {
            oldItem.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 0);
        }
    }

    /**
     * 根据id设置产品是否为自选
     */
    private void updateSelectTickList(int isSelect, int uiCode) {
        if (mTickMap.containsKey(uiCode + "")) {
            DataItemDetail itemDetail = mTickMap.get(uiCode + "");
            itemDetail.setIntValue(GTSConst.JSON_KEY_ISSELECTED, isSelect);
        }
    }

    /**
     * 添加自选
     */
    public void addSelfTick(DataItemDetail model) {
        int code = model.getInt(GTSConst.JSON_KEY_CODEID);
        Logger.i(TAG, "addSelfTick code = " + code);
        updateSelectTickList(1, code);
        mSelfCode.add(code);
        RxBus.getInstance().post(GTSConst.REPLY_SWITCH_QUOTE_EDIT_BTN, false);
    }

    public void addSelfTickToFirst(DataItemDetail model) {
        updateSelectTickList(1, model.getInt(GTSConst.JSON_KEY_CODEID));
        mSelfCode.add(0, model.getInt(GTSConst.JSON_KEY_CODEID));
    }

    /**
     * 删除自选产品
     */
    public void removeSelfTick(DataItemDetail model) {
        int code = model.getInt(GTSConst.JSON_KEY_CODEID);
        Logger.i(TAG, "removeSelfTick code = " + code);
        updateSelectTickList(0, code);
        String modelString = code + "";
        String selfString;
        for (int i = 0; i < mSelfCode.size(); i++) {
            selfString = mSelfCode.get(i).toString();
            if (selfString.equals(modelString)) {
                mSelfCode.remove(i);
                break;
            }
        }
        validateSelfTick();
        RxBus.getInstance().post(GTSConst.REPLY_SWITCH_QUOTE_EDIT_BTN, false);
    }

    /**
     * 过滤掉自选产品的数据,编辑界面调用
     */
    public DataItemResult getFilterTickList(String type) {
        DataItemResult mList = new DataItemResult();
        Iterator<String> keys = mTickMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            DataItemDetail item = mTickMap.get(key);
            if (null != item && item.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE
                    && item.getInt(GTSConst.JSON_KEY_ISSELECTED) != 1) {
                if (type.equals(item.getInt(GTSConst.JSON_KEY_ZONE) + "") || type.equals(GTSConst.ZONE_TYPE_ALL + "")) {
                    mList.addItem(item);
                }
            }
        }
        Collections.sort(mList.getDataList(), new Comparator<DataItemDetail>() {
            @Override
            public int compare(DataItemDetail o1, DataItemDetail o2) {
                if (null != o1 && null != o2) {
                    if (o1.getInt(GTSConst.JSON_KEY_ZONE) == o2.getInt(GTSConst.JSON_KEY_ZONE)) {
                        return StringUtils.sortPro(o2.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME), o1.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
                    } else if (o1.getInt(GTSConst.JSON_KEY_ZONE) > o2.getInt(GTSConst.JSON_KEY_ZONE)) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
                return 0;
            }
        });
        return mList;
    }

    /**
     * 根据类型返回第一个可以交易的行情对象
     */
    public DataItemDetail getTradeTickModel() {
        DataItemResult result = getTickList(GTSConst.ZONE_TYPE_FX + "");
        if (result.getDataCount() < 1) {
            result = getTickList(GTSConst.ZONE_TYPE_ALL + "");
        }
        if (result.getDataCount() > 0) {
            for (DataItemDetail item : result.getDataList()) {
                if (item.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_ABLE) {
                    return item;
                }
            }
        }
        return null;
    }

    /**
     * 根据类型和uicode返回行情对象
     */
    public DataItemDetail getTickModel(int uiCode) {
        if (mTickMap.containsKey(uiCode + "")) {
            return mTickMap.get(uiCode + "");
        }

        return null;
    }

    public DataItemDetail getTickModelByName(String name) {
        if (TextUtils.isEmpty(name)) {
            return null;
        }
        for (Map.Entry<String, DataItemDetail> me : mTickMap.entrySet()) {
            DataItemDetail value = me.getValue();
            if (value != null) {
                String prdName = value.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB);
                if (name.equals(prdName)) {
                    return value;
                }
            }
        }
        return null;
    }

    /**
     * 获取需要订阅报价的产品id,包含当前类型和持仓数据
     */
    public ArrayList getQuoteSubscribeCodes(String type) {
        HashSet<Integer> hashSet = new HashSet<Integer>();
        if (type.equals(GTSConst.ZONE_TYPE_SELF + "")) {
            Logger.e("订阅产品：自选产品数量" + mSelfCode.size());
            for (int i = 0; i < mSelfCode.size(); i++) {
                DataItemDetail item = mTickMap.get(mSelfCode.get(i).toString());
                if (null != item && item.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE) {
                    hashSet.add(DoubleConverter.toIntData(mSelfCode.get(i).toString()));
                }
            }
        } else {
            Iterator<String> keys = mTickMap.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                DataItemDetail item = mTickMap.get(key);
                if (null != item && (type.equals(item.getInt(GTSConst.JSON_KEY_ZONE) + "")
                        || type.equals(GTSConst.ZONE_TYPE_ALL + ""))
                        && item.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE
                        && item.getInt(GTSConst.JSON_KEY_CODEID) != 0) {
                    hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEID));
                }
            }
        }

        DataItemResult mList = mPositionInfoList;
        for (int j = 0; j < mList.getDataCount(); j++) {
//            Logger.e("gw.com.android", "mPositionInfoList.get(j).uiCode == " + mList.get(j).uiCode +", " + mList.get(j).uiOppoCode);
            DataItemDetail item = mList.getItem(j);
            if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) != 0) {
                hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEID));
                if (item.getInt(GTSConst.JSON_KEY_CODEMIDDLE) != 0) {
                    hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEMIDDLE));
                }
            }
        }

        DataItemResult mList2 = mOrderInfoList;
        for (int j = 0; j < mList2.getDataCount(); j++) {
//            Logger.e("gw.com.android", "mPositionInfoList.get(j).uiCode == " + mList.get(j).uiCode +", " + mList.get(j).uiOppoCode);
            DataItemDetail item = mList2.getItem(j);
            if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) != 0) {
                hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEID));
            }
        }

        //人民币账号固定订阅美元人民币产品
        if (isCNY()) {
            hashSet.add(GTSConst.CNY_CODE);
        }

        ArrayList<Integer> codeList = new ArrayList<Integer>();
        codeList.addAll(hashSet);
        //判断是否与上次请求一致，一致的话不重复发送请求
        if (codeList.containsAll(mCodes) && mCodes.containsAll(codeList)) {
            Logger.e("订阅产品：产品重复了,不发送订阅！！！");
            return null;
        } else {
            mCodes.clear();
            mCodes.addAll(codeList);
        }

        return codeList;
    }

    /**
     * 获取需要订阅报价的产品id,图表，下单相关界面调用
     */
    public ArrayList getQuoteSubscribeCode(int code) {
        HashSet<Integer> hashSet = new HashSet<Integer>();
        if (0 != code) {
            hashSet.add(code);
        }

        DataItemResult mList = mPositionInfoList;
        for (int j = 0; j < mList.getDataCount(); j++) {
//            Logger.e("gw.com.android", "mPositionInfoList.get(j).uiCode == " + mList.get(j).uiCode +", " + mList.get(j).uiOppoCode);
            DataItemDetail item = mList.getItem(j);
            if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) != 0) {
                hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEID));
                if (item.getInt(GTSConst.JSON_KEY_CODEMIDDLE) != 0) {
                    hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEMIDDLE));
                }
            }
        }

        DataItemResult mList2 = mOrderInfoList;
        for (int j = 0; j < mList2.getDataCount(); j++) {
//            Logger.e("gw.com.android", "mOrderInfoList.get(j).uiCode == " + mList2.get(j).uiCode);
            DataItemDetail item = mList2.getItem(j);
            if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) != 0) {
                hashSet.add(item.getInt(GTSConst.JSON_KEY_CODEID));
            }
        }

        //人民币账号固定订阅美元人民币产品
        if (isCNY()) {
            hashSet.add(GTSConst.CNY_CODE);
        }

        ArrayList<Integer> codeList = new ArrayList<>();
        codeList.addAll(hashSet);
        //判断是否与上次请求一致，一致的话不重复发送请求
        if (codeList.containsAll(mCodes) && mCodes.containsAll(codeList)) {
            Logger.e("订阅产品：产品重复了,不发送订阅！！！");
            return null;
        } else {
            mCodes.clear();
            mCodes.addAll(codeList);
        }

        return codeList;
    }

    /**
     * 设置发送订阅的codelist
     */
    public void setQuoteCodes(ArrayList codeList) {
        mCodes.clear();
        mCodes.addAll(codeList);
    }

    /**
     * 返回自选股codes集合
     *
     * @return
     */
    public ArrayList<Integer> getSelfCodes() {
        return mSelfCode;
    }

    /**
     * 添加持仓列表数据
     */
    public void addPositionList(String jsonStr) {
        try {
            mPositionInfoList.clear();
            mPositionNumMap.clear();
            JSONArray mArray = new JSONArray(jsonStr);
            JsonUtil.toDataItemResult(mPositionInfoList, mArray);
            for (int i = 0; i < mPositionInfoList.getDataCount(); i++) {
                int code = mPositionInfoList.getItem(i).getInt(GTSConst.JSON_KEY_CODEID);
                Integer num = 0;
                if (mPositionNumMap.containsKey(code + "")) {
                    num = mPositionNumMap.get(code + "");
                }
                mPositionNumMap.put(code + "", num + 1);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 报价更新后更新持仓数据
     */
    public ArrayList<Integer> updatePositionList(int code, String jsonStr) {
        HashSet<Integer> hashSet = new HashSet<Integer>();
        hashSet.add(code);
        try {
            JSONArray mArray = new JSONArray(jsonStr);
            for (int i = 0; i < mArray.length(); i++) {
                JSONObject model = mArray.getJSONObject(i);
                for (int j = 0; j < mPositionInfoList.getDataCount(); j++) {
                    if (model.getInt(GTSConst.JSON_KEY_ID) == mPositionInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                        hashSet.add(model.getInt(GTSConst.JSON_KEY_CODEID));
                        updatePositionItem(mPositionInfoList.getItem(j), model);
                        break;
                    }
                }
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
        ArrayList<Integer> codeList = new ArrayList<>();
        codeList.addAll(hashSet);
        return codeList;
    }

    /**
     * 持仓数据更新单条数据
     */
    public void updateOnePosition(String jsonStr) {
        try {
            JSONObject mArray = new JSONObject(jsonStr);
            for (int j = 0; j < mPositionInfoList.getDataCount(); j++) {
                if (mArray.optInt(GTSConst.JSON_KEY_ID) == mPositionInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                    updatePositionItem(mPositionInfoList.getItem(j), mArray);
                    Logger.e("updateOnePosition = " + mPositionInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID) + ", " + mPositionInfoList.getItem(j).getString(GTSConst.JSON_KEY_ORDERPRICE)
                            + ", " + mPositionInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPLOSS) + ", " + mPositionInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPPROFIT));
                    break;
                }
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 持仓盈亏对象更新
     */
    private void updatePositionItem(DataItemDetail oldItem, JSONObject newItem) {
        //报价更新
        if (newItem.optInt(GTSConst.JSON_KEY_BUYPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_BUYPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_BUYPRICESTATE));
            oldItem.setIntValue(GTSConst.JSON_KEY_BUYPRICEARRAW, 0);
        } else {
            oldItem.setIntValue(GTSConst.JSON_KEY_BUYPRICEARRAW, 1);
        }
        if (newItem.optInt(GTSConst.JSON_KEY_SELLPRICESTATE) != 0) {
            oldItem.setIntValue(GTSConst.JSON_KEY_SELLPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_SELLPRICESTATE));
            oldItem.setIntValue(GTSConst.JSON_KEY_SELLPRICEARRAW, 0);
        } else {
            oldItem.setIntValue(GTSConst.JSON_KEY_SELLPRICEARRAW, 1);
        }

        oldItem.setStringValue(GTSConst.JSON_KEY_OPENPRICE, newItem.optString(GTSConst.JSON_KEY_OPENPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_BUYPRICE, newItem.optString(GTSConst.JSON_KEY_BUYPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_SELLPRICE, newItem.optString(GTSConst.JSON_KEY_SELLPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_ZOOMRULE, newItem.optString(GTSConst.JSON_KEY_ZOOMRULE));
        oldItem.setStringValue(GTSConst.JSON_KEY_INTEREST, newItem.optString(GTSConst.JSON_KEY_INTEREST));
        oldItem.setStringValue(GTSConst.JSON_KEY_COMMISSION, newItem.optString(GTSConst.JSON_KEY_COMMISSION));
        oldItem.setStringValue(GTSConst.JSON_KEY_ORDERPRICE, newItem.optString(GTSConst.JSON_KEY_ORDERPRICE));
        oldItem.setStringValue(GTSConst.JSON_KEY_STOPLOSS, newItem.optString(GTSConst.JSON_KEY_STOPLOSS));
        oldItem.setStringValue(GTSConst.JSON_KEY_STOPPROFIT, newItem.optString(GTSConst.JSON_KEY_STOPPROFIT));
        oldItem.setStringValue(GTSConst.JSON_KEY_PROFIT, newItem.optString(GTSConst.JSON_KEY_PROFIT));

        oldItem.setIntValue(GTSConst.JSON_KEY_USEDIP, newItem.optInt(GTSConst.JSON_KEY_USEDIP));
        oldItem.setIntValue(GTSConst.JSON_KEY_EXPIRETYPE, newItem.optInt(GTSConst.JSON_KEY_EXPIRETYPE));
        oldItem.setIntValue(GTSConst.JSON_KEY_PROFITSTATE, newItem.optInt(GTSConst.JSON_KEY_PROFITSTATE));
        oldItem.setIntValue(GTSConst.JSON_KEY_STOPLOSSSTATE, newItem.optInt(GTSConst.JSON_KEY_STOPLOSSSTATE));
        oldItem.setIntValue(GTSConst.JSON_KEY_STOPPROFITSTATE, newItem.optInt(GTSConst.JSON_KEY_STOPPROFITSTATE));
        oldItem.setIntValue(GTSConst.JSON_KEY_ORDERPRICESTATE, newItem.optInt(GTSConst.JSON_KEY_ORDERPRICESTATE));
        oldItem.setIntValue(GTSConst.JSON_KEY_TIME, newItem.optInt(GTSConst.JSON_KEY_TIME));
        oldItem.setIntValue(GTSConst.JSON_KEY_POS_UPDATETIME, newItem.optInt(GTSConst.JSON_KEY_POS_UPDATETIME));
        oldItem.setIntValue(GTSConst.JSON_KEY_ORDERTYPE, newItem.optInt(GTSConst.JSON_KEY_ORDERTYPE));
        oldItem.setIntValue(GTSConst.JSON_KEY_DIRECTION, newItem.optInt(GTSConst.JSON_KEY_DIRECTION));
        oldItem.setStringValue(GTSConst.JSON_KEY_VOLUME, newItem.optString(GTSConst.JSON_KEY_VOLUME));

        oldItem.setIntValue(GTSConst.JSON_KEY_TRADESTATE, newItem.optInt(GTSConst.JSON_KEY_TRADESTATE));
        oldItem.setIntValue(GTSConst.JSON_KEY_DIGITS, newItem.optInt(GTSConst.JSON_KEY_DIGITS));
    }

    /**
     * 持仓数据添加单条数据
     */
    public void addOnePositionList(String jsonStr) {
        try {
            JSONObject mArray = new JSONObject(jsonStr);
            DataItemDetail item = new DataItemDetail();
            JsonUtil.toDataItemDetail(item, mArray);
            DataItemDetail tick = mTickMap.get(item.getInt(GTSConst.JSON_KEY_CODEID) + "");
            if (null != tick) {
                item.setIntValue(GTSConst.JSON_KEY_BUYPRICESTATE, tick.getInt(GTSConst.JSON_KEY_BUYPRICESTATE));
                item.setIntValue(GTSConst.JSON_KEY_SELLPRICESTATE, tick.getInt(GTSConst.JSON_KEY_SELLPRICESTATE));
                item.setIntValue(GTSConst.JSON_KEY_BUYPRICEARRAW, tick.getInt(GTSConst.JSON_KEY_BUYPRICEARRAW));
                item.setIntValue(GTSConst.JSON_KEY_SELLPRICEARRAW, tick.getInt(GTSConst.JSON_KEY_SELLPRICEARRAW));
            }
            if (mPositionInfoList.getDataCount() > 0) {
                mPositionInfoList.addItem(0, item);
            } else {
                mPositionInfoList.addItem(item);
            }
            int code = item.getInt(GTSConst.JSON_KEY_CODEID);
            Integer num = 0;
            if (mPositionNumMap.containsKey(code + "")) {
                num = mPositionNumMap.get(code + "");
            }
            mPositionNumMap.put(code + "", num + 1);
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 删除position数据
     */
    public void removePosition(int posId) {
        for (int j = 0; j < mPositionInfoList.getDataCount(); j++) {
            DataItemDetail newItem = mPositionInfoList.getItem(j);
            if (newItem.getInt(GTSConst.JSON_KEY_ID) == posId) {
                Logger.e("removePosition id is " + posId);
                mPositionInfoList.removeByIndex(j);
                int code = newItem.getInt(GTSConst.JSON_KEY_CODEID);
                Integer num = 0;
                if (mPositionNumMap.containsKey(code + "")) {
                    num = mPositionNumMap.get(code + "");
                }
                if (num > 0) {
                    num = num - 1;
                }
                mPositionNumMap.put(code + "", num);
                break;
            }
        }
    }

    /**
     * 返回持仓数量
     */
    public int getPositionNum(int code) {
        Integer num = 0;
        if (mPositionNumMap.containsKey(code + "")) {
            num = mPositionNumMap.get(code + "");
        }
        return num;
    }

    /**
     * 根据持仓id获取持仓数据
     */
    public DataItemDetail getPositionModel(int id) {
        Logger.i(TAG, "getPositionModel = " + id);
        for (int j = 0; j < mPositionInfoList.getDataCount(); j++) {
            Logger.e("getPositionModel = " + j + " ," + mPositionInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID));
            if (id == mPositionInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                Logger.e("getPositionModel = " + mPositionInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID) + ", " + mPositionInfoList.getItem(j).getString(GTSConst.JSON_KEY_ORDERPRICE)
                        + ", " + mPositionInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPLOSS) + ", " + mPositionInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPPROFIT));
                return mPositionInfoList.getItem(j);
            }
        }
        return null;
    }

    /**
     * 获取某一个产品的所有持仓
     *
     * @param codeId 产品Id
     * @return 返回一个DataItemResult对象，包含该产品的所有持仓，以及  该产品持仓的总盈亏， 总买手， 总买入盈利， 总卖手， 总卖出盈利等信息 # GTSConst.JSON_KEY_POSITION_TOTAL_*
     */
    public DataItemResult getPositionByCodeId(int codeId) {
        DataItemResult list = new DataItemResult();
        if (mPositionInfoList == null) {
            return list;
        }

        // 该产品的持仓信息
        for (int i = 0; i < mPositionInfoList.getDataCount(); i++) {
            if (mPositionInfoList.getItem(i).getInt(GTSConst.JSON_KEY_CODEID) == codeId) {
                list.addItem(mPositionInfoList.getItem(i));
            }
        }

        // 计算 盈利，手数等信息
        // 总盈亏
        double totalProfit = 0.00;
        // 总买手
        double totalBuyLots = 0.00;
        // 总买入盈利
        double totalBuyProfit = 0.00;
        // 总卖手
        double totalSellLots = 0.00;
        // 总卖出盈利
        double totalSellProfit = 0.00;

        for (int i = 0; i < list.getDataCount(); i++) {
            DataItemDetail item = list.getItem(i);
            double lots = DoubleConverter.toDoubleData(item.getString(GTSConst.JSON_KEY_VOLUME));
            double profit = DoubleConverter.toDoubleData(item.getString(GTSConst.JSON_KEY_PROFIT));
            totalProfit += profit;
            if (item.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY) {
                totalBuyLots += lots;
                totalBuyProfit += profit;
            } else {
                totalSellLots += lots;
                totalSellProfit += profit;
            }
        }

        list.detailInfo.setStringValue(GTSConst.JSON_KEY_POSITION_TOTAL_PROFITS, DoubleConverter.toStringData(totalProfit));
        list.detailInfo.setStringValue(GTSConst.JSON_KEY_POSITION_TOTAL_BUY_LOTS, DoubleConverter.toStringData(totalBuyLots));
        list.detailInfo.setStringValue(GTSConst.JSON_KEY_POSITION_TOTAL_BUY_PROFITS, DoubleConverter.toStringData(totalBuyProfit));
        list.detailInfo.setStringValue(GTSConst.JSON_KEY_POSITION_TOTAL_SELL_LOTS, DoubleConverter.toStringData(totalSellLots));
        list.detailInfo.setStringValue(GTSConst.JSON_KEY_POSITION_TOTAL_SELL_PROFITS, DoubleConverter.toStringData(totalSellProfit));
        return list;
    }


    /**
     * 添加挂单列表数据
     */
    public void addOrderList(String jsonStr) {
        try {
            mOrderInfoList.clear();
            JSONArray mArray = new JSONArray(jsonStr);
            JsonUtil.toDataItemResult(mOrderInfoList, mArray);
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 根据更新时间排序集合对象
     */
    public DataItemResult getSortOrderList(DataItemResult tmp) {
        if (null == tmp) {
            return null;
        }
        final DataItemResult sortList = new DataItemResult();
        sortList.appendItems(tmp);
        try {
            if (sortList.getDataCount() > 0) {
                Collections.sort(sortList.getDataList(), new Comparator<DataItemDetail>() {
                    @Override
                    public int compare(DataItemDetail o1, DataItemDetail o2) {
                        if (null != o1 && null != o2) {

                            if (o1.getInt(GTSConst.JSON_KEY_TIME) > o2.getInt(GTSConst.JSON_KEY_TIME)) {
                                return -1;
                            } else if (o1.getInt(GTSConst.JSON_KEY_TIME) == o2.getInt(GTSConst.JSON_KEY_TIME)) {
                                if (o2.getInt(GTSConst.JSON_KEY_ID) > o1.getInt(GTSConst.JSON_KEY_ID)) {
                                    return 1;
                                } else if (o2.getInt(GTSConst.JSON_KEY_ID) == o1.getInt(GTSConst.JSON_KEY_ID)) {
                                    return 0;
                                } else {
                                    return -1;
                                }
                            } else {
                                return 1;
                            }
                        } else {
                            return 0;
                        }
                    }
                });
            }
        } catch (Exception e) {
            Logger.e(TAG, e);
        }
        return sortList;
    }

    /**
     * 报价更新后更新挂单数据
     */
    public void updateOrderList(String jsonStr) {
        try {
            JSONArray mArray = new JSONArray(jsonStr);
            for (int i = 0; i < mArray.length(); i++) {
                JSONObject model = mArray.getJSONObject(i);
                for (int j = 0; j < mOrderInfoList.getDataCount(); j++) {
                    if (model.optInt(GTSConst.JSON_KEY_ID) == mOrderInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                        updatePositionItem(mOrderInfoList.getItem(j), model);
                        break;
                    }
                }
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 挂单数据更新单条数据
     */
    public void updateOneOrderList(String jsonStr) {
        try {
            JSONObject mArray = new JSONObject(jsonStr);
            for (int j = 0; j < mOrderInfoList.getDataCount(); j++) {
                if (mArray.optInt(GTSConst.JSON_KEY_ID) == mOrderInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                    updatePositionItem(mOrderInfoList.getItem(j), mArray);
                    Logger.e("updateOneOrderList = " + mOrderInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID) + ", " + mOrderInfoList.getItem(j).getString(GTSConst.JSON_KEY_ORDERPRICE)
                            + ", " + mOrderInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPLOSS) + ", " + mOrderInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPPROFIT));
                    break;
                }
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 根据id返回挂单对象
     */
    public DataItemDetail getOrderModel(int id) {
        Logger.e("getOrderModel = " + id);
        for (int j = 0; j < mOrderInfoList.getDataCount(); j++) {
            Logger.e("getOrderModel = " + j + " ," + mOrderInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID));
            if (id == mOrderInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                Logger.e("getOrderModel = " + mOrderInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID) + ", " + mOrderInfoList.getItem(j).getString(GTSConst.JSON_KEY_ORDERPRICE)
                        + ", " + mOrderInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPLOSS) + ", " + mOrderInfoList.getItem(j).getString(GTSConst.JSON_KEY_STOPPROFIT));
                return mOrderInfoList.getItem(j);
            }
        }

        return null;
    }

    /**
     * 挂单数据添加单条数据
     */
    public void addOneOrderList(String jsonStr) {
        try {
            JSONObject mArray = new JSONObject(jsonStr);
            DataItemDetail item = new DataItemDetail();
            JsonUtil.toDataItemDetail(item, mArray);
            DataItemDetail tick = mTickMap.get(item.getInt(GTSConst.JSON_KEY_CODEID) + "");
            if (null != tick) {
                item.setIntValue(GTSConst.JSON_KEY_BUYPRICESTATE, tick.getInt(GTSConst.JSON_KEY_BUYPRICESTATE));
                item.setIntValue(GTSConst.JSON_KEY_SELLPRICESTATE, tick.getInt(GTSConst.JSON_KEY_SELLPRICESTATE));
                item.setIntValue(GTSConst.JSON_KEY_BUYPRICEARRAW, tick.getInt(GTSConst.JSON_KEY_BUYPRICEARRAW));
                item.setIntValue(GTSConst.JSON_KEY_SELLPRICEARRAW, tick.getInt(GTSConst.JSON_KEY_SELLPRICEARRAW));
            }
            if (mOrderInfoList.getDataCount() > 0) {
                mOrderInfoList.addItem(0, item);
            } else {
                mOrderInfoList.addItem(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 挂单数据删除单条数据
     */
    public void removeOrder(int posId) {
        for (int j = 0; j < mOrderInfoList.getDataCount(); j++) {
            DataItemDetail newItem = mOrderInfoList.getItem(j);
            if (newItem.getInt(GTSConst.JSON_KEY_ID) == posId) {
                Logger.e("removeOrder id is " + posId);
                mOrderInfoList.removeByIndex(j);
                break;
            }
        }
    }

    /**
     * 添加当时成交列表数据
     */
    public void addDealList(String jsonStr) {
        try {
            mDealInfoList.clear();
            JSONArray mArray = new JSONArray(jsonStr);
            JsonUtil.toDataItemResult(mDealInfoList, mArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 当日成交数据添加单条数据
     */
    public void addOneDealList(DataItemDetail item) {
        if (mDealInfoList.getDataCount() > 0) {
            mDealInfoList.addItem(0, item);
        } else {
            mDealInfoList.addItem(item);
        }
    }


    /**
     * 根据id返回当日成交对象
     */
    public DataItemDetail getOpenDealModel(int id) {
        for (int j = 0; j < mDealInfoList.getDataCount(); j++) {
            if (id == mDealInfoList.getItem(j).getInt(GTSConst.JSON_KEY_POSID)) {
                return mDealInfoList.getItem(j);
            }
        }
        return null;
    }

    public DataItemDetail getCloseDealModel(int id) {
        for (int j = 0; j < mDealInfoList.getDataCount(); j++) {
            if (id == mDealInfoList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                return mDealInfoList.getItem(j);
            }
        }
        return null;
    }

    /**
     * 添加当时盈亏列表数据
     */
    public void addCloseList(String jsonStr) {
        try {
            mCloseList.clear();
            JSONArray mArray = new JSONArray(jsonStr);
            JsonUtil.toDataItemResult(mCloseList, mArray);
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 当日盈亏数据添加单条数据
     */
    public void addOneCloseList(String jsonStr) {
        try {
            JSONObject mArray = new JSONObject(jsonStr);
            DataItemDetail item = new DataItemDetail();
            JsonUtil.toDataItemDetail(item, mArray);
            if (mCloseList.getDataCount() > 0) {
                mCloseList.addItem(0, item);
            } else {
                mCloseList.addItem(item);
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
    }


    /**
     * 根据id返回当日盈亏对象
     */
    public DataItemDetail getCloseModel(int id) {
        Logger.e("getCloseModel = " + id);
        for (int j = 0; j < mCloseList.getDataCount(); j++) {
            Logger.e("getCloseModel = " + j + " ," + mCloseList.getItem(j).getInt(GTSConst.JSON_KEY_ID));
            if (id == mCloseList.getItem(j).getInt(GTSConst.JSON_KEY_ID)) {
                Logger.e("getCloseModel = " + mCloseList.getItem(j).getInt(GTSConst.JSON_KEY_ID) + ", " + mCloseList.getItem(j).getString(GTSConst.JSON_KEY_ORDERPRICE)
                        + ", " + mCloseList.getItem(j).getString(GTSConst.JSON_KEY_CLOSEPRICE));
                return mCloseList.getItem(j);
            }
        }
        return null;
    }

    /**
     * 根据语言从对象中获取产品名
     */
    public String getPrdName(DataItemDetail item) {
        if (null == item) {
            return "";
        }
        if (GTConfig.instance().getLanguage().equals(GTConfig.LANG_ZH_CN)) {
            return item.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB);
        } else {
            return item.getString(GTSConst.JSON_KEY_SYMBOLNAMEBIG);
        }
    }

    /**
     * 设置界面数据加载状态，true标识加载完成，false标识未完成
     */
    public void setLoadDataState(String tag, boolean isLoaded) {
        mLoadDataStateMap.put(tag, isLoaded);
    }

    /**
     * 获取界面数据加载状态，true标识加载完成，false标识未完成
     */
    public boolean getLoadDataState(String tag) {
        if (mLoadDataStateMap.containsKey(tag)) {
            return mLoadDataStateMap.get(tag);
        }
        return false;
    }

}
